package org.algorithm.wE1.链表;

import java.util.HashMap;
import java.util.Map;

/***
 * @Task 2022/2/21
 * @Link  {https://leetcode-cn.com/problems/lru-cache/}
 */
public class LRUCache {

    //构建双向链表
    class DLinkNode{
        int key;
        int value;
        DLinkNode pre;
        DLinkNode next;
        DLinkNode(int key, int value){
            this.key = key;
            this.value = value;
        }
        DLinkNode(){}
    }
    private int size;
    private int capacity;
    private Map<Integer,DLinkNode> cache = new HashMap<>();
    private DLinkNode head = new DLinkNode();
    private DLinkNode tail = new DLinkNode();
    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        //cache 中查看时候有key如果没有 直接返回-1
        DLinkNode node = cache.get(key);
        if(node == null){
            return -1;
        }
        //如果存在 将节点移动至头部，并返回node.value
        moveToHead(node);
        return  node.value;
    }


    public void put(int key, int value) {
        //cache 中查看时候有key如果没有 在头部添加
        DLinkNode node = cache.get(key);
        if(node == null){
            DLinkNode newNode = new DLinkNode(key,value);
            saveHeadNode(newNode);
            cache.put(key,newNode);
            ++size;
            //添加之后 如果链表长度大于限定值时 删除尾部节点 并在cache中删除
            if(size>capacity){
                DLinkNode tailNode = removeTail();
                cache.remove(tailNode.key);
                --size;
            }
        }else{
            //如果存在 将其赋新的值，并移动到头部
            node.value = value;
            moveToHead(node);
        }
    }

    private DLinkNode removeTail() {
        DLinkNode tailNode = tail.pre;
        removeNode(tailNode);
        return tailNode;
    }

    private void moveToHead(DLinkNode node) {
        removeNode(node);
        saveHeadNode(node);
    }

    private void saveHeadNode(DLinkNode node) {
        node.pre = head;
        head.next.pre = node;
        node.next = head.next;
        head.next = node;
    }

    private void removeNode(DLinkNode node) {
        node.next.pre = node.pre;
        node.pre.next = node.next;
    }

}
